#include "assitant.h"

#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;

void printw(const response_data& result) {
    print(result.ec, result.status, result.resp_body, result.resp_headers.second);
}

Assitant::Assitant()
{
    auto s = "/home/td/Temp/WallPic/test1.png";
    auto filename = fs::path(s).filename().string();
    // std::cout << filename << "\n";
}



void Assitant::getNewPic(std::string url, std::string target)
{
    auto client = cinatra::client_factory::instance().new_client();
    if(target.empty()){
        // target = "/home/td/Temps/WallPic/"+getYearMonthDay()+".jpg";
        target = "/home/td/Temps/WallPic/By.jpg";
    }
    std::cout <<url<<"\n";
    client->download(url, target.c_str(), [](response_data data) {
        if (data.ec) {
            std::cout << data.ec.message() << "\n";
            return;
        }
        std::cout <<"下载完成 \n";
    });
}

/**
 * @brief Assitant::getImgUrl
 * @param url  url
 * @param key  解析所用的key
 * @return
 */
std::string Assitant::getImgUrl(std::string url, std::string key)
{

}

std::string Assitant::getCurrentTime()
{
    std::time_t result = std::time(nullptr);
    return std::ctime(&result);
}

//获取年月日(命名用)
std::string Assitant::getYearMonthDay()
{
    time_t timer;
    time(&timer);
    tm* t_tm = localtime(&timer);

    std::string Year=std::to_string(t_tm->tm_year+1900);
    std::string Month=std::to_string(t_tm->tm_mon+1);
    std::string Day=std::to_string(t_tm->tm_mday);
    std::string PictureName=Year+"_"+Month+"_"+Day;

    return PictureName;
}

void Assitant::getHH()
{
    std::string retUrl="https://api.zwho.me/image/360";
    auto client = cinatra::client_factory::instance().new_client();
    client->async_get(retUrl, [](response_data data) {
        std::cout << data.resp_body << "\n";
        printw(data);
    });
}



//获取图片的Xml并解析图片的url路径
std::string Assitant::getPicTureXmlAndUrl()
{
    //网络上的XML路径
    std::string WebXmlpath ="https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1";
    std::string retUrl="http://www.httpwatch.com/httpgallery/chunked/chunkedimage.aspx";
    auto client = cinatra::client_factory::instance().new_client();
    client->async_get(WebXmlpath, [&retUrl](response_data data) {

        Fast::config val1(data.resp_body,"json");
        auto val = val1.getChild("images",0);
        std::string byUrl = "https://cn.bing.com/" +  val.get<std::string>("url");
        retUrl = byUrl;
        // std::cout << data.resp_body << "\n";
        // std::cout << "url:" << val.get<std::string>("url") << "\n";
        // std::cout << "enddate:" << val.get<std::string>("enddate") << "\n";
        // printw(data);
        // std::cout << retUrl << "\n";
    });
    return retUrl;
}
